package com.doge.walknovel.payment.google

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import com.doge.wnpro.R
import com.doge.walknovel.core.BaseFragment
import com.doge.walknovel.utils.log

class AppBillingClientFragment : BaseFragment() {
    private val appBillingClient by lazy { AppBillingClientLifecycle.get() }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return View(inflater.context)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        appBillingClient.purchaseSyncedMissedEvent.observe(viewLifecycleOwner) {
            it?.let {
                log("AppBillingClientFragment appBillingClient missed synced")
                activity?.supportFragmentManager?.beginTransaction()
                    ?.remove(this)?.commitAllowingStateLoss()
            }
        }
        log("AppBillingClientFragment appBillingClient setup silently")
        appBillingClient.setup(lifecycle, refer = null, silently = true)
    }

    companion object {
        fun attach(activity: FragmentActivity) {
            log( "AppBillingClientFragment attach to $activity")
            activity.supportFragmentManager.beginTransaction()
                .replace(R.id.google, AppBillingClientFragment(), "AppBillingClient")
                .commitAllowingStateLoss()
        }
    }
}